//
//  SearchFriendViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/1.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "SearchFriendViewController.h"
#import "CeShiModelOfFriendMessage.h"
#import "FriendMessageTableViewCell.h"
#import "MyChatViewController.h"
#import "ZGWSearchFriendModel.h"
#import "FriendIDCheckViewController.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface SearchFriendViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UISearchBar *mySearchBar;

@property (nonatomic, strong) NSMutableArray *searchFriendArray; // 搜索好友数据源
@property (nonatomic, strong) UITableView *friendTableview; // 好友tableview

@property (nonatomic, assign) BOOL canClickGuanZhu; // 是否可以点击关注

@end

@implementation SearchFriendViewController

- (void)viewWillDisappear:(BOOL)animated
{
    // 结束动画
    [[JiaZaiAnimationHandle                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                shareJiaZaiAnimationHandle] stopAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 添加searchBar
    [self addSearchBar];
    // 建立刚进来就显示的数据
    [self addFirstShowData];
    // 添加好友tableview
    [self addFriendTableview];
    self.canClickGuanZhu = YES;
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:22]};
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:84 / 255.0 green:199 / 255.0 blue:222 / 255.0 alpha:1]];
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 添加searchBar
- (void)addSearchBar
{
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 260, 30)];
    self.mySearchBar.barStyle = UIBarStyleDefault;
    self.mySearchBar.delegate = self;
    self.mySearchBar.placeholder = @"输入好友的名字";
    self.mySearchBar.tintColor = kCyanColor;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 260, 30)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 4 * kAdjustParamater;
    view.layer.masksToBounds = YES;
    view.userInteractionEnabled = YES;
    [view addSubview:_mySearchBar];
    self.navigationItem.titleView = view;
}

#pragma mark - UISearchBar代理

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//    self.searchFriendArray = [NSMutableArray array];
//    NSLog(@"text = %@", searchText);
//    NSDictionary *dicFriend1 = @{@"_friendImage": @"", @"_name": @"张国文", @"_gender": @"男", @"_myID": @"987654321", @"_mark": @[@"健康达人", @"我爱看电影你呢"]};
//    NSDictionary *dicFriend2 = @{@"_friendImage": @"", @"_name": @"张慧杰", @"_gender": @"女", @"_myID": @"123456789", @"_mark": @[@"我是运动达人", @"爱看电影"]};
//    NSArray *tempArray = [NSArray arrayWithObjects:dicFriend1, dicFriend2, nil];
//    for (NSDictionary *tempDic in tempArray) {
//        if ([[tempDic valueForKey:@"_name"] containsString:searchText]) {
//            CeShiModelOfFriendMessage *tempModel = [[CeShiModelOfFriendMessage alloc] init];
//            [tempModel setValuesForKeysWithDictionary:tempDic];
//            [self.searchFriendArray addObject:tempModel];
//        }
//
//    }
//    
//    [self.friendTableview reloadData];
}

#pragma mark - 建立一进来就显示的数据
- (void)addFirstShowData
{
    
    
    // 取出最后以用户的搜索名字
    NSString *lastName = [[NetStatusHandle shareHandle] getLastSearchFriendName];
    
    if (lastName.length == 0) {
        
    } else {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];

        // 在每次内容改的情况下初始化数据源数组
        self.searchFriendArray = [NSMutableArray array];
        // 搜索好友的url
        NSString *searchFriendUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWSearchFriend, kCurrentUserToken];
        NSDictionary *paramaterDic = @{@"nikename":lastName};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:searchFriendUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
            if (!responseObject) {
                return;
            }
            NSArray *personArray = [responseObject valueForKey:@"persons"];
            
            
            for (NSDictionary *friendDic in personArray) {
                ZGWSearchFriendModel *searchModel = [[ZGWSearchFriendModel alloc] init];
                [searchModel setValuesForKeysWithDictionary:friendDic];
                [self.searchFriendArray addObject:searchModel];
            }
            //     NSLog(@"搜索数据源 = %@", self.searchFriendArray);
            [self.friendTableview reloadData];
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"数据请求失败，请重试" ToView:self];
        }];
    }
    

}

#pragma mark - 添加好友tableview
- (void)addFriendTableview
{
    self.friendTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.friendTableview.dataSource = self;
    self.friendTableview.delegate = self;
    [self.view addSubview:_friendTableview];
    self.friendTableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

// tableview代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchFriendArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *identifier = @"friendMessage";
//    FriendMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    if (cell == nil) {
//        cell = [[FriendMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//    }
    // 这里cell不能服用
    static NSString *identifier = @"friendMessage";
    FriendMessageTableViewCell *cell = [[FriendMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 获取model
    if (self.searchFriendArray.count > indexPath.row) {
        cell.zgwSearchFriendModel = self.searchFriendArray[indexPath.row];
    }
    
    [cell.attentionButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButton.tag = 200;
    [cell.addFriendButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.addFriendButton.tag = 201;
    return cell;
}

#pragma mark - button的点击事件
- (void)clickButton:(UIButton *)button
{
    UIView *v = [button superview];
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[v superview];
    NSIndexPath *tempIndexPath = [self.friendTableview indexPathForCell:cell];
    switch (button.tag) {
        case 200:
        {
            // 说明是关注好友
            NSLog(@"关注好友, row = %ld", tempIndexPath.row);
            ZGWSearchFriendModel *searchModel = self.searchFriendArray[tempIndexPath.row];
            NSString *isAttention = [NSString stringWithFormat:@"%@", searchModel.is_attention];
            if ([isAttention isEqualToString:@"1"]) {
                NSLog(@"已经关注");
            } else if ([isAttention isEqualToString:@"0"]) {
                NSLog(@"进行关注");
                if (self.canClickGuanZhu == YES) {
                    self.canClickGuanZhu = NO;
                    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
                    // 关注url
                    NSString *attentionUserUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWAttentionUser, kCurrentUserToken];
                    NSDictionary *paramaterDic = @{@"attention_user":searchModel.user_id};
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    [manager POST:attentionUserUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        self.canClickGuanZhu = YES;
                        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                        NSString *msgString = [statusDic valueForKey:@"msg"];
                        if ([msgString isEqualToString:@"关注成功"]) {
                            searchModel.is_attention = [NSString stringWithFormat:@"%d", 1];
                            [self.friendTableview reloadData];
                        }
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提醒" Content:@"关注失败" ToView:self];
                        self.canClickGuanZhu = YES;
                    }];
                }

            }
            break;
        }
         case 201:
        {
            // 说明是添加好友
            NSLog(@"添加好友,row = %ld", tempIndexPath.row);
            ZGWSearchFriendModel *searchModel = self.searchFriendArray[tempIndexPath.row];
            NSString *isFriend = [NSString stringWithFormat:@"%@", searchModel.is_friend];
            if ([isFriend isEqualToString:@"1"]) {
                NSLog(@"已经是好友");
            } else if ([isFriend isEqualToString:@"0"]) {
                NSLog(@"添加好友");
                FriendIDCheckViewController *friendIDCheckVC = [[FriendIDCheckViewController alloc] init];
                
                friendIDCheckVC.targetUserID = searchModel.user_id;
                friendIDCheckVC.currentUserName = searchModel.nikename;
                [self.navigationController pushViewController: friendIDCheckVC animated:YES];
            }
            break;
        }
        default:
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
    myChatVC.conversationType = ConversationType_PRIVATE;
    if (self.searchFriendArray.count > indexPath.row) {
        ZGWSearchFriendModel *model = self.searchFriendArray[indexPath.row];
        NSLog(@"姓名:%@", model.nikename);
        myChatVC.targetId = model.user_id;
        myChatVC.title = model.nikename;
    }
    
    [self.navigationController pushViewController:myChatVC animated:YES];

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 动态布局
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[self tableView:self.friendTableview cellForRowAtIndexPath:indexPath];
    return cell.geneSimilarityLabel.bottom + 13 * kAdjustParamater;
}

// 取消键盘
-  (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    
    // 在每次内容改的情况下初始化数据源数组
    self.searchFriendArray = [NSMutableArray array];
    // 搜索好友的url
    NSString *searchFriendUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWSearchFriend, kCurrentUserToken];
    NSDictionary *paramaterDic = @{@"nikename":searchBar.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:searchFriendUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if (!responseObject) {
            return;
        }
        NSArray *personArray = [responseObject valueForKey:@"persons"];
        if (personArray.count == 0) {
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertNoTitieWithContent:@"暂时没有该用户" toView:self];
        } else {
            // 保存当前搜索的名字
            [[NetStatusHandle shareHandle] saveLastSearchFriendName:searchBar.text];
        }
        
        for (NSDictionary *friendDic in personArray) {
            ZGWSearchFriendModel *searchModel = [[ZGWSearchFriendModel alloc] init];
            [searchModel setValuesForKeysWithDictionary:friendDic];
            [self.searchFriendArray addObject:searchModel];
        }
   //     NSLog(@"搜索数据源 = %@", self.searchFriendArray);
        [self.friendTableview reloadData];
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"数据请求失败，请重试" ToView:self];
    }];

    
    [searchBar resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
